package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.app.dao.AddressDao;
import io.renren.modules.app.entity.AddressEntity;
import io.renren.modules.app.service.AddressService;
import org.springframework.transaction.annotation.Transactional;


@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, AddressEntity> implements AddressService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AddressEntity> page = this.page(
                new Query<AddressEntity>().getPage(params),
                new QueryWrapper<AddressEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 获取用户地址
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public AddressEntity getUserAddress(Long userId) {
        QueryWrapper<AddressEntity> wrapper = new QueryWrapper<>();
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        wrapper.last("limit 1");
        return baseMapper.selectOne(wrapper);
    }


    /**
     * 修改用户地址
     *
     * @param address 地址信息
     * @return
     */
    @Override
    public Integer editUserAddress(AddressEntity address) {
        UpdateWrapper<AddressEntity> updateWrapper = new UpdateWrapper<>();
        if (address.getUserId() != null) {
            updateWrapper.eq("user_id", address.getUserId());
        }
        return baseMapper.update(address, updateWrapper);
    }


    /**
     * 新增用户地址
     *
     * @param address 地址信息
     * @return
     */
    @Transactional
    @Override
    public Integer addUserAddress(AddressEntity address) {
        address.setCreateTime(new Date());
        return baseMapper.insert(address);
    }

}